package com.oauth.TickGranter;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 自定义认证
 * @author ysy
 */
public class TickGranter extends AbstractTokenGranter {

    private static final  String GRANT_TYPE="cas_tick";

    private final AuthenticationManager authenticationManager;

    public TickGranter(AuthenticationManager authenticationManager
            , AuthorizationServerTokenServices tokenServices
            , ClientDetailsService clientDetailsService
            , OAuth2RequestFactory requestFactory) {

        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;

    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> requestParameters = tokenRequest.getRequestParameters();
        //接收传入的参数
        String token = requestParameters.get("token");
        //利用第一个构造方法来创建一个实例
        Authentication userAuth = new CasTickAuthenticationToken(token);
        //把用户传入的参数交给自定义的Token
        ((AbstractAuthenticationToken) userAuth).setDetails(requestParameters);
        userAuth = authenticationManager.authenticate(userAuth);
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate cas: " + token);
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
